import { useState, useRef, useEffect } from "react";
import {
  Upload,
  Button,
  Input,
  Card,
  Row,
  Col,
  Statistic,
  Divider,
  message,
  Tooltip,
} from "antd";
import {
  InboxOutlined,
  LockOutlined,
  UnlockOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import { imgToolsData } from "@/components/ToolsData";
import ToolTitle from "@/components/ToolTitle";

const { Dragger } = Upload;

const ImageResizer = () => {
  const [originalSize, setOriginalSize] = useState({ width: 0, height: 0 });
  const [targetSize, setTargetSize] = useState({ width: 0, height: 0 });
  const [lockAspect, setLockAspect] = useState(true);
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const imageRef = useRef<HTMLImageElement>(new Image());

  useEffect(() => {
    if (originalSize.width > 0) {
      processImage();
    }
  }, [targetSize]);

  const handleFile = (file: File) => {
    if (!file.type.startsWith("image/")) {
      message.error("请选择图片文件");
      return false;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      imageRef.current.src = e.target?.result as string;
      imageRef.current.onload = () => {
        setOriginalSize({
          width: imageRef.current.naturalWidth,
          height: imageRef.current.naturalHeight,
        });
        setTargetSize({
          width: imageRef.current.naturalWidth,
          height: imageRef.current.naturalHeight,
        });
        processImage();
      };
    };
    reader.readAsDataURL(file);
    return false;
  };

  const processImage = () => {
    if (!canvasRef.current || !imageRef.current.src) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    canvas.width = targetSize.width;
    canvas.height = targetSize.height;

    ctx.drawImage(imageRef.current, 0, 0, targetSize.width, targetSize.height);
    setProcessedImage(canvas.toDataURL());
  };

  const handleDimensionChange = (
    dimension: "width" | "height",
    value: number
  ) => {
    const newValue = Math.max(0, value);

    if (lockAspect && originalSize.width > 0 && originalSize.height > 0) {
      const aspect = originalSize.width / originalSize.height;
      const newSize =
        dimension === "width"
          ? { width: newValue, height: Math.round(newValue / aspect) }
          : { width: Math.round(newValue * aspect), height: newValue };
      setTargetSize(newSize);
    } else {
      setTargetSize((prev) => ({
        ...prev,
        [dimension]: newValue,
      }));
    }
  };

  const downloadImage = () => {
    if (!processedImage) return;

    const link = document.createElement("a");
    link.download = `resized-image-${Date.now()}.png`;
    link.href = processedImage;
    link.click();
  };

  return (
    <div className="p-4">
      <Card bordered={false} className="shadow-md">
        <ToolTitle
          title={
            imgToolsData.find((item) => item.title === "图片宽高修改")?.title ||
            ""
          }
          description={
            imgToolsData.find((item) => item.title === "图片宽高修改")
              ?.description || ""
          }
        />
        <Divider />

        <Dragger
          accept="image/*"
          beforeUpload={handleFile}
          showUploadList={false}
          className="mb-4"
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">拖拽图片到此区域或点击选择</p>
          <p className="ant-upload-hint">
            支持格式：JPG/JPEG/PNG/GIF/WEBP/SVG/ICO
          </p>
        </Dragger>

        {originalSize.width > 0 && (
          <div>
            <Row gutter={16} className="mb-4 mt-4">
              <Col span={12}>
                <Input
                  addonBefore="宽度"
                  suffix="px"
                  value={targetSize.width}
                  onChange={(e) =>
                    handleDimensionChange(
                      "width",
                      parseInt(e.target.value) || 0
                    )
                  }
                />
              </Col>
              <Col span={12}>
                <Input
                  addonBefore="高度"
                  suffix="px"
                  value={targetSize.height}
                  onChange={(e) =>
                    handleDimensionChange(
                      "height",
                      parseInt(e.target.value) || 0
                    )
                  }
                  addonAfter={
                    <Tooltip
                      title={
                        lockAspect ? "点击解除宽高比锁定" : "点击锁定当前宽高比"
                      }
                      placement="bottom"
                    >
                      <Button
                        icon={
                          lockAspect ? <LockOutlined /> : <UnlockOutlined />
                        }
                        onClick={() => setLockAspect(!lockAspect)}
                      />
                    </Tooltip>
                  }
                />
              </Col>
            </Row>

            <Row gutter={16} className="mb-4">
              <Col span={24}>
                <div
                  className="border rounded p-4"
                  style={{
                    backgroundImage: `
                      linear-gradient(45deg, #f0f0f0 25%, transparent 25%),
                      linear-gradient(-45deg, #f0f0f0 25%, transparent 25%),
                      linear-gradient(45deg, transparent 75%, #f0f0f0 75%),
                      linear-gradient(-45deg, transparent 75%, #f0f0f0 75%)
                    `,
                    backgroundSize: "20px 20px",
                    backgroundPosition: "0 0, 0 10px, 10px -10px, -10px 0px",
                  }}
                >
                  {processedImage ? (
                    <img
                      src={processedImage}
                      alt="处理结果"
                      className="mx-auto block bg-white"
                      style={{
                        maxWidth: "100%",
                        maxHeight: "60vh",
                        transition: "all 0.3s",
                        boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                      }}
                    />
                  ) : (
                    <div className="text-gray-400 text-center py-8">
                      图片预览区域
                    </div>
                  )}
                  <canvas ref={canvasRef} style={{ display: "none" }} />
                </div>
              </Col>
            </Row>

            <Row gutter={16} className="mb-4">
              <Col>
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={downloadImage}
                >
                  下载图片
                </Button>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Statistic
                  title="原始宽度"
                  value={originalSize.width}
                  suffix="px"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="原始高度"
                  value={originalSize.height}
                  suffix="px"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="缩放比例"
                  value={(
                    (targetSize.width / originalSize.width) *
                    100
                  ).toFixed(1)}
                  suffix="%"
                />
              </Col>
            </Row>
          </div>
        )}
      </Card>
    </div>
  );
};

export default ImageResizer;
